package com.example.assisteddriving.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.telephony.SmsManager;
import android.util.Log;

import androidx.annotation.Nullable;

import com.example.assisteddriving.Zhuye;
import com.example.assisteddriving.util.LocationUtils;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Jiujiasevice extends Service {
    ServerSocket ss2;
    Socket socket2;
    Thread jiujiathread;
    Runnable jiujiatask;
    String phoneNuml;
    private Message msg;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCE_NAME, MODE);
        phoneNuml = sharedPreferences.getString("jinjidianhua", null);
        jiujiatask = new Runnable() {
            @Override
            public void run() {
                try {
                    ss2 = new ServerSocket(10009);
                    while (true) {
                        Log.v("asd", "酒精检测等待连接");
                        socket2 = ss2.accept();
                        Log.v("asd", "酒精检测已连接");
                        //接收
                        BufferedReader br = null;
                        br = new BufferedReader(new InputStreamReader(socket2.getInputStream()));
                        String line = br.readLine();
                        Log.v("asd", line);
                        if (line.equals("e")) {

                            callPhone();

                        }

                        br.close();
                        socket2.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        //关闭输入流、socket
                        if (socket2 != null) socket2.close();
                        if (ss2 != null) ss2.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        jiujiathread = new Thread(jiujiatask);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!jiujiathread.isAlive()) {
            jiujiathread.start();
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (jiujiathread.isAlive()) {
            Log.v("asd", "酒精服务已结束");
            try {
                if (socket2 != null) socket2.close();
                if (ss2 != null) ss2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        msg = new Message(); //也可msg = Message.obtain();
        msg.what = 0x002; //设置消息类型
        Bundle data1 = new Bundle(); //生成Bundle对象携带数据
        data1.putString("msg","destroy");
        msg.setData(data1);
        Zhuye.myHandler.sendMessage(msg);
    }
//    private boolean getCallLogState() {
//        ContentResolver cr = getContentResolver();
//        final Cursor cursor = cr.query(CallLog.Calls.CONTENT_URI,
//                new String[]{CallLog.Calls.NUMBER,CallLog.Calls.TYPE,CallLog.Calls.DURATION},
//                CallLog.Calls.NUMBER +"=? and "+CallLog.Calls.TYPE +"= ?",
//                new String[]{mobile.getText().toString(),"CallLog.Calls.TYPE"},null);
//        while(cursor.moveToNext()){
//            int durationIndex = cursor.getColumnIndex(CallLog.Calls.DURATION);
//            long durationTime = cursor.getLong(durationIndex);
//            if(durationTime > 0){
//                isLink = true;
//            } else {
//                isLink = false;
//            }
//        }
//        return false;
//    }
    public void sendSMS2(String phoneNumber,String message) {

        if (!phoneNumber.isEmpty() && !message.isEmpty()) {
            SmsManager smsManager = SmsManager.getDefault();
            ArrayList<String> strings = smsManager.divideMessage(message);
            for (int i = 0; i < strings.size(); i++) {
                smsManager.sendTextMessage(phoneNumber, null, message, null, null);
            }
            Log.v("asd","短信已发送");
        } else {
            Log.v("asd","手机号不能为空");
            return;
        }
    }
    public static final String PREFERENCE_NAME = "gerenxinxi";  //文件名
    public static int MODE = MODE_PRIVATE;  //操作模式

    public void callPhone(){

        Log.v("asd",phoneNuml);
        //如果需要手动拨号将Intent.ACTION_CALL改为Intent.ACTION_DIAL（跳转到拨号界面，用户手动点击拨打）
        Intent intent =new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNuml));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
        startActivity(intent);
    }
}



